如果你的Python環境沒有requests模組
pip install requests
向網站/網路資源請求資料(request),主要有GET/POST兩種方式,如果溝通正常,通常會獲得回應response,除了資料外還會有一個http status code,關於網路HTTP具體技術細節這邊不會講解,有興趣可以自行Google
個人建議會重複使用的常數都集中寫在設定檔案中,再用ConfigParser讀取,這樣可以統一修改整份專案的常數
[Server]
#永豐消費支付API服務網址
Api_URL = https://apisbx.sinopac.com/funBIZ/QPay.WebAPI/api/Order
#永豐消費支付API-Nonce服務網址
Nonce_URL = https://apisbx.sinopac.com/funBIZ/QPay.WebAPI/api/Nonce
API以Json格式溝通,建立一個基本的Json Headers
jsonheaders = {
'Content-Type': 'application/json'
}
實作發送request
#讀取設定檔
env = ConfigParser()
env.read('env.ini')
cfg = SimpleNamespace(Api_URL = env['Server']['Api_URL'], Nonce_URL = env['Server']['Nonce_URL'])
#發送POST的request
def sendreq(method="POST", url = None, headers=jsonheaders, data = None):
try:
response = requests.request(method=method, url=url, headers=headers, data=data)
return response
except Exception as err:
print(err)
產生JSON格式的Request實作
def GenRequest(cfg, APIService, sign, nonce, message):
req = {'Version':cfg.Version, 'ShopNo':cfg.ShopNo, 'APIService':APIService, 'Sign':sign, 'Nonce': nonce, 'Message':message}
#ensure_ascii=False,關閉中文ascii轉換
js_req = json.dumps(req, indent=4, ensure_ascii=False)
return js_req
返回的Response中的參數定義可以參考w3schools,實際會使用到的只有statud_code與content
#判斷是否Ok
response.OK
# TRUE/FALSE
#將content轉成str
response.text
#將content轉成json
response.json()
說明請見數位金流 API 技術規格文件p.13,以下為完成簽章與內文加密的完整Request
{
"Version": "1.0.0",
"ShopNo": "NA0001_001",
"APIService": "OrderCreate",
"Sign": "7788EE61DD450944992641B3B2F8210B81A0AE97908BC19825F2A82C0F72EA43",
"Nonce": "NjM2NjY5MDQ3OTQwMzIuMTphZmJjODBhOTM5NzQ1NjMyNDFhZTczMjVjYzg0Mjg5ZjQxYTk2MWI2ZjNkYTA0NDdmOTRhZjU3ZTIzOWJlNDgz",
"Message": "4FE341D3A8C30C9A50573F3008F7B1CA8DD96FB2A4346D83936E5C4FDB21E87BA9E3D36A6635C6F5EBBD5438F3CA8FE97DEBB2ADBC82F92BF3C840B3128D8F00116536E7C936D7D587F6220C52C1367DF2BE9CBB16C6A7C6242AA8B38CD2E576328CF727E50FFA49B4F9FBE5DF10986C5299F9FC26E23E956AFDFB92B731FDA84ABEF1C89E0CD0A8CA8F7C23DC2D06E12A6F916EC47CDD9B4D4F87AC0B687EE1088A19F2C35C0FD8B0C97745B926FBAA48FEEDEB826C2C22743DB46781FF220ECA409FC150908540271E60184729C08C73275C54125C3F814FF33CA79A0E1B3902D446925FCC8235809FCBAB7E372D8C29E424CEFF0AD1CBD41E843714EB365158F2FC0B2E6FB48176D5CFF6B68F4BED4D7484C1A4723ABD059DA64A6703B30B0199B170FDF059899552FA1818ABA5B0D0E21014513985A738D59851EDF0B1CFB36A7B7B727109BE7789D284C75E5D694DFC9B7060DCBFD8C7915C95C4E0F29B"
}
最後一個Message參數怎麼看不懂,安啦明天將說明如何進行內文的ABS CBC加密